//
//  OauthViewController.swift
//  Sina
//
//  Created by 邹志华 on 15/11/8.
//  Copyright © 2015年 zzh. All rights reserved.
//

import UIKit
import SVProgressHUD

class OauthViewController: UIViewController {

    
    override func loadView() {
        view = webView
        
        //设置代理
        webView.delegate = self
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        view.backgroundColor = UIColor.brownColor()
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        //加载网页
        let request = NSURLRequest(URL: NetworkTools.sharedInstance.oauthRUL())
        webView.loadRequest(request)
    }

    ///关闭控制器
    func close () {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    //MARK: - 懒加载
    private lazy var webView = UIWebView()

}

//MARK: - UIWebViewDelegate代理
extension OauthViewController: UIWebViewDelegate
{
    
    
    ///开始加载请求
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.showWithStatus("从服务器加载中..",maskType:SVProgressHUDMaskType.Black)
    
    }
    
    
    ///        加载请求完毕
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭加载
        SVProgressHUD.dismiss()
    }
    
    
    ///询问是否加载 request
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        print("urlString:\(urlString)")
        
        
        //判断是不是回调地址http://weibo.com/jiushixiaoyan/?code=7ca1bd004d27a6718e59fd5c835e2c15
        
        //加载的不是回调地址
        if !urlString.hasPrefix(NetworkTools.sharedInstance.redirect_uri) {
            
            return true //可以加载
        }
        
        
        //如果点击的是确定或取消就拦截不加载
        /*
        
       weibo.com/jiushixiaoyan/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        
        */
        
        if let query = request.URL?.query {
            
            print("query:\(query)")
            let codeString = "code="
            if query.hasPrefix(codeString) {
                //确定
                //7ca1bd004d27a6718e59fd5c835e2c15
                
                //转换
                let nsQuery = query as NSString
                
                //截取code
                   let code = nsQuery.substringFromIndex(codeString.characters.count)
                
                print("code:\(code)")
                //获取access token
                
                loadAccessToken(code)
            }else{
 
                //取消
            }  
        }
        
        return false
    }
   //加载access token 
    //调用网络工具类去加载access token
    func loadAccessToken(code:String){
        
        NetworkTools.sharedInstance.loadAccessToken(code) {(result,error) ->() in
            if error != nil || result == nil {
                SVProgressHUD.showErrorWithStatus("网络不给力..", maskType: SVProgressHUDMaskType.Black)
                
                
                //延迟关闭 SVProgressHUD.showErrorWithStatus
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.close()
                })
                
                return
            }
        
        print("result:\(result)")
          let accoun =  UserAcoount(dict: result!)
            //保存到沙盒
            accoun.saveAccount()
            print("accoun:\(accoun)")
            SVProgressHUD.dismiss()
        }
    }
}
